<template>
  <el-form ref="deptForm" label-width="120px" :model="form" :rules="rules">
    <el-form-item label="部门名称" prop="name">
      <el-input
        v-model="form.name"
        style="width: 80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input
        v-model="form.code"
        style="width: 80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width: 80%" placeholder="请选择">
        <el-option
          v-for="item in user"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input
        v-model="form.introduce"
        style="width: 80%"
        placeholder="1-300个字符"
        type="textarea"
        :rows="3"
      />
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        size="small"
        @click="dodepartment(id)"
      >确定</el-button>
      <el-button size="small">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getUser } from '@/api/empioyees'
import {
  adddepartment,
  updatedepartment,
  adddepartmentList
} from '@/api/department'

export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 自定义检验规则
    const validName = (rule, value, callback) => {
      // 筛选出同级数据,再取出其名字抛到一个新数组
      let existNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)

      if (this.isEdit) {
        // 当页面为编辑状态时,筛选与当前id相符的数据,获取pid
        const pid = this.originList.find(item => item.id === this.id).pid
        // 过滤掉包含当前pid的数据
        const brothers = this.originList.filter(item => item.pid === pid)
        // 重新筛选出同级数据,取出名称
        existNameList = brothers.filter(item => item.id !== this.id).map(item => item.name)
      }

      // 筛选出数组是否包含当前输入的名称
      if (existNameList.includes(value)) {
        callback(new Error(`该部门 ${value} 已存在`))
      } else {
        callback()
      }
    }

    // 自定义校验,验证部门编码的唯一性
    const validCode = (rule, value, callback) => {
      // 取出originList中的code
      let existCodeList = this.originList.map((item) => item.code)
      console.log(existCodeList, 'existCodeList')

      // 如果是编辑状态,则将当前编辑部门的数据从存储的数据中删除,在进行判断
      if (this.isEdit) {
        existCodeList = this.originList
          .filter((item) => item.id !== this.id)
          .map((item) => item.code)
      }

      // 筛选当前value是否存在
      if (existCodeList.includes(value)) {
        callback(new Error(`该部门编码${value}已存在`))
      } else {
        callback()
      }
    }

    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      user: [],
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '长度在 1 到 50 个字符',
            trigger: 'blur'
          },
          { validator: validName, trigger: 'blur' }
        ], // 部门名称

        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '长度在 1 到 50 个字符',
            trigger: 'blur'
          },
          { validator: validCode, trigger: 'blur' }
        ], // 部门编码

        manager: [
          { required: true, message: '请选择部门管理者', trigger: 'change' }
        ], // 部门管理者

        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          {
            min: 1,
            max: 300,
            message: '长度在 1 到 300 个字符',
            trigger: 'blur'
          }
        ] // 部门介绍
      }
    }
  },
  created() {
    // 页面加载获取数据
    this.doUser()
    // 当为编辑页面的时候获取部门详细数据
    if (this.isEdit) {
      this.addDepartmentList()
    }
  },
  methods: {
    // 获取部门负责人列表
    async doUser() {
      try {
        const res = await getUser()
        this.user = res.data
        console.log(res.data, 'user')
      } catch (error) {
        console.log(error)
      }
    },
    // 点击确认
    dodepartment() {
      // 兜底校验
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return
        this.isEdit ? this.updepartment() : this.newdepartment()
        // 子传父自定义组件关闭弹层并重新渲染数据
        this.$emit('closePop')
      })
    },
    // 添加部门
    async newdepartment() {
      try {
        await adddepartment({ ...this.form, pid: this.id })
      } catch (error) {
        console.log(error)
      }
    },
    // 修改部门
    async updepartment() {
      try {
        await updatedepartment(this.form)
      } catch (error) {
        console.log(error)
      }
    },
    // 获取部门详细信息
    async addDepartmentList() {
      const res = await adddepartmentList(this.id)
      this.form = res.data
      console.log(res.data, '部门详细信息')
    }
  }
}
</script>

<style>
</style>
